package dslab.core;

import dslab.util.Pair;

import java.io.IOException;
import java.io.Writer;

/**
 * interface specifying what a generic protocol implementation should offer
 */
public interface Protocol {

    /**
     * announces spoken protocols at connection the start of the connection
     * @param out Writer object extracted containing socket output stream to write to
     */
    void initMessage(Writer out) throws IOException;

    /**
     * warning handler that signals to the client that something has gone wrong;
     * the connection stays alive.
     * @param out Writer of the connection to the client to write warning to
     * @param warning warning to write
     * @throws IOException in case of a broken connection or writer an exception is thrown
     */
    void raiseWarning(Writer out, String warning) throws IOException;

    /**
     * error handler that signals to the client that something has gone fatally wrong;
     * the connection gets closed directly after
     * @param out Writer of the connection to the client to write warning to
     * @param error error to write
     * @throws IOException in case of a broken connection or writer an exception is thrown
     */
    void raiseError(Writer out, String error) throws IOException;

    // obsolete?
    /**
     * helper method that will always be needed, for instance to split a request into body and header
     * @param payload text to be split into a pair
     * @param delimiter delimiter to split with
     * @return pair of Strings
     * @throws IllegalArgumentException thrown if the payload does not contain the delimiter
     */
    default Pair<String, String> split(String payload, String delimiter) throws IllegalArgumentException {
        // check for delimiter
        if (!payload.contains(delimiter))
            throw new IllegalArgumentException();

        // make the split
        var split = payload.split(delimiter, 2);
        return new Pair<>(split[0], split[1]);
    }
}
